/**
 * Copyright (C) 2010  Johan Basson
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>
 */

package symorg.io;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.Vector;

/**
 * Reads a text file into multiple lines.
 * 
 * @author johan
 */
public class FileReader {

    public static Vector read(InputStream in) throws IOException {
        Reader reader = null;
        Vector items = new Vector();
        char[] buffer = new char[1024];
        StringBuffer sb = new StringBuffer();
        int read = 0;

        /* Read contents into memory */
        try {
            reader = new InputStreamReader(in);
            do {
                read = reader.read(buffer);
                if (read != -1) {
                    sb.append(buffer, 0, read);
                }
            } while (read != -1);
        } finally {
            reader.close();
        }


        /* Tokenize each line */
        char[] data = sb.toString().toCharArray();
        int pos = 0;
        sb = null;
        StringBuffer buf = new StringBuffer();
        do {
            if (data[pos] == '\n' || data[pos] == '\r') {
                buf.append(data[pos]);
            } else {
                items.addElement(buf.toString());
                buf.setLength(0);
            }
        } while (pos < data.length);


        return items;
    }

    public static Vector readLines(InputStream in) throws IOException {
        Reader reader = null;
        int read = 0;
        char[] buffer = new char[1024];
        Vector items = new Vector();
        StringBuffer sb = new StringBuffer();

        try {
            reader = new InputStreamReader(in);
            do {
                read = reader.read(buffer);
                if (read != -1) {
                    for (int t=0;t < read;t++) {
                        if (buffer[t] == '\n' || buffer[t] == '\r'){
                            items.addElement(sb.toString());
                            sb.setLength(0);
                        } else {
                            sb.append(buffer[t]);
                        }
                    }
                }
            } while (read != -1);
            return items;
        } finally {
            reader.close();
        }
    }
}
